package com.xtx.air.web.action.login;


import com.google.code.jcaptcha4struts2.common.actions.JCaptchaBaseAction;
import com.xtx.air.bo.operator.IOperatorBO;
import com.xtx.air.dataobject.OperatorDO;
import com.xtx.air.web.action.BaseAction;
import com.xtx.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.List;

public class LoginAction extends JCaptchaBaseAction {
    private OperatorDO oper = new OperatorDO();
    private IOperatorBO operatorBO;
    protected Log logger = LogFactory.getLog(this.getClass());

    public String login() {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            return SUCCESS;
        } else {
            return INPUT;
        }
    }

    public String doLogin() {
        String userName = oper.getOperLogName();
        String password = oper.getOperLogPwd();
        AuthenticationToken token = new UsernamePasswordToken(userName, password);
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            return SUCCESS;
        } else {
            try {
                if (StringUtil.isEmpty(userName) && StringUtil.isEmpty(password)) {
                    return INPUT;
                }
                currentUser.login(token);
                List<String> permissions = operatorBO.findOperatorPermission(currentUser.getPrincipal().toString());
                Session session = currentUser.getSession();
                session.setAttribute("permission", permissions);
                return SUCCESS;
            } catch (UnknownAccountException e) {
                addActionError("不存在的账户");
            } catch (IncorrectCredentialsException e) {
                addActionError("用户名密码不匹配");
            } catch (Exception e) {
                logger.error("登录发生异常", e);
                addActionError("登录发生异常，请稍后再试");
            }
        }
        return INPUT;
    }

    public String logoff() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return SUCCESS;
    }

    public OperatorDO getOper() {
        return oper;
    }

    public void setOper(OperatorDO oper) {
        this.oper = oper;
    }

    public IOperatorBO getOperatorBO() {
        return operatorBO;
    }

    public void setOperatorBO(IOperatorBO operatorBO) {
        this.operatorBO = operatorBO;
    }
}
